# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict
from common.utils.tz import local_now
import requests
from django.conf import settings
import time
from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {

    '10107': {  # 富宝通支付 支付宝h5 100-5000 3.3% witch
        'API_KEY': 'cvuidomo5aus55s8632kqrj8ibr6n86p',
        'gateway': 'http://pay.ywoxb.cn/Pay_Index.html',
        'query_gateway': 'http://pay.ywoxb.cn/Pay_pay_orderQurey.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] and k != 'body' and k != 'sign':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % str(key)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    calculated_sign = generate_sign(params, key)
    if params['sign'] != calculated_sign:
        _LOGGER.info("fubaotongpay sign: %s, calculated sign: %s", params['sign'], calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_pay_type(service):
    if service == 'alipay_h5':
        return '942'
    elif service == 'alipay_scan':
        return '903'
    return '903'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('bank_id', _get_pay_type(service)),
        ('out_trade_no', str(pay.id)),
        ('mch_id', app_id),
        ('total_fee', '%.2f' % pay_amount),
        ('return_url', '{}/pay/api/{}/fubaotongpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notify_url', '{}/pay/api/{}/fubaotongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('apply_date', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('body', 'charge'),
        ('attach', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("fubaotongpay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['out_trade_no'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('fubaotongpay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("fubaotongpay notify data: %s", data)
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s", data)
        raise ParamError('fubaotongpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['returncode']
    trade_no = data['order_no']
    total_fee = float(data['total_fee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0':
        _LOGGER.info('fubaotongpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('out_trade_no', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('fubaotongpay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['out_trade_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('fubaotongpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['pay_status'])  # 订单已完成, 订单未完成
        total_fee = float(data['total_fee'])
        trade_no = str(pay_order.third_id)
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 0失败，1为支付成功，未返回，2支付成功，已返回
        if trade_status in ['1', '2']:
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('fubaotongpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('fubaotongpay data error, status_code: %s', response.status_code)
